package com.huang.lochy;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.TextView;
import com.dk.uartnfc.Card.IDCardListener;
import com.dk.uartnfc.DKCloudID.IDCardData;
import com.dk.uartnfc.DeviceManager.IdCardReader;

public class MainActivity extends AppCompatActivity {
    final static String TAG = "DKCloudID";
    private TextView msgTextView;
    static long time_start = 0;
    static long time_end = 0;

    private IdCardReader idCardReader;

    private ProgressDialog readWriteDialog = null;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //读卡器初始化
        idCardReader = new IdCardReader(deviceManagerCallback);
        //启动2秒后再打开读卡器
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if ( idCardReader.openDevice("/dev/ttyUSB0") ) {
                    logViewln("读卡器打开成功，请刷卡");
                }
                else {
                    logViewln("读卡器打开失败，请检查串口号是否正确！");
                }
            }
        }).start();

        iniview();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭读卡器
        idCardReader.closeDevice();
    }

    //设备操作类回调
    private IDCardListener deviceManagerCallback = new IDCardListener() {
        //身份证开始请求云解析回调
        @Override
        public void onReadIDCardStart() {
            super.onReadIDCardStart();

            Log.d(TAG, "开始解析");
            logViewln(null);
            logViewln("正在读卡，请勿移动身份证!");

            time_start = System.currentTimeMillis();
        }

        //身份证云解析异常回调
        @Override
        public void onReadIDCardError(int reason) {
            super.onReadIDCardError(reason);

            //显示错误信息
            logViewln("身份证读取失败，reason:" + reason);

            //读卡结束关闭进度条显示
            hidDialog();
        }

        //身份证云解析明文结果回调
        @Override
        public void onReadIDCardComplete(IDCardData idCardData) {
            super.onReceiveIDCardData(idCardData);
            showIDMsg(idCardData);
        }

        //身份证云解析进度回调
        @Override
        public void onReceiveSamVIdSchedule(int rate) {
            super.onReceiveSamVIdSchedule(rate);
            showReadWriteDialog("正在读取身份证信息,请不要移动身份证", rate);
            if (rate == 100) {
                time_end = System.currentTimeMillis();
            }
        }

        //卡片离开回调
        @Override
        public void onReceiveCardLeave() {
            super.onReceiveCardLeave();
            Log.d(TAG, "卡片已离开");
            logViewln("卡片已离开");
        }
    };

    private void iniview() {
        msgTextView = (TextView) findViewById(R.id.msgText);

        readWriteDialog = new ProgressDialog(MainActivity.this);
        readWriteDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 标题
        readWriteDialog.setTitle("请稍等");
        // 设置ProgressDialog 提示信息
        readWriteDialog.setMessage("正在读写数据……");
        readWriteDialog.setMax(100);
    }

    private void logViewln(String string) {
        final String msg = string;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg == null) {
                    msgTextView.setText("");
                    return;
                }

                if (msgTextView.length() > 1000) {
                    msgTextView.setText("");
                }
                msgTextView.append(msg + "\r\n");
                int offset = msgTextView.getLineCount() * msgTextView.getLineHeight();
                if(offset > msgTextView.getHeight()){
                    msgTextView.scrollTo(0,offset-msgTextView.getHeight());
                }
            }
        });
    }

    private void showIDMsg(IDCardData msg) {
        final IDCardData idCardData = msg ;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                msgTextView.setText("解析成功，读卡用时:" + (time_end - time_start) + "ms\r\n" + idCardData.toString() + "\r\n");

                SpannableString ss = new SpannableString(msgTextView.getText().toString()+"[smile]");
                //得到要显示图片的资源
                Drawable d = new BitmapDrawable(idCardData.PhotoBmp);
                if (d != null) {
                    //设置高度
                    d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                    //跨度底部应与周围文本的基线对齐
                    ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
                    //附加图片
                    ss.setSpan(span, msgTextView.getText().length(),msgTextView.getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    msgTextView.setText(ss);
                }
            }
        });
    }

    //进度条显示
    private void showReadWriteDialog(String msg, int rate) {
        final int theRate = rate;
        final String theMsg = msg;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if ((theRate == 0) || (theRate == 100)) {
                    readWriteDialog.dismiss();
                    readWriteDialog.setProgress(0);
                } else {
                    readWriteDialog.setMessage(theMsg);
                    readWriteDialog.setProgress(theRate);
                    if (!readWriteDialog.isShowing()) {
                        readWriteDialog.show();
                    }
                }
            }
        });
    }

    //隐藏进度条
    private void hidDialog() {
        //关闭进度条显示
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (readWriteDialog.isShowing()) {
                    readWriteDialog.dismiss();
                }
                readWriteDialog.setProgress(0);
            }
        });
    }
}
